package com.ifcar.app.service;

import java.io.File;
import java.text.SimpleDateFormat;

import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.IBinder;
import android.util.Log;

import com.ifcar.app.activity.MyApplication;
import com.ifcar.app.bean.DetailPageBean;
import com.ifcar.app.db.NewsSQLiteOpenHelper;
import com.ifcar.app.util.FileUtils;
import com.ifcar.app.util.PicUtil;

public class ClearCacheService extends IntentService {

	public ClearCacheService() {
        super("ClearCacheService");
    }

    @Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

    @Override
    protected void onHandleIntent(Intent intent) {
        MyApplication app = (MyApplication)this.getApplicationContext();
        SQLiteDatabase db = app.getSQLiteDatabase();
        
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");     
        String date = sDateFormat.format(new java.util.Date(
                System.currentTimeMillis()-DetailPageBean.ExpiredDuration)); 
        String statusDate = sDateFormat.format(new java.util.Date(
                System.currentTimeMillis()-DetailPageBean.StutusExpiredDuration));
        try {
            db.execSQL("delete from "+NewsSQLiteOpenHelper.NEWS_LIST_TABLE + " where " +
                    NewsSQLiteOpenHelper.NEWS_PTIME + "< '" + date + "'");
            db.execSQL("delete from "+NewsSQLiteOpenHelper.COMMENTS_LIST_TABLE + " where " +
                    NewsSQLiteOpenHelper.COMMENTS_PTIME + "< '" + date + "' and " +
                    NewsSQLiteOpenHelper.COMMENTS_COL_ID + "= 'top'");
            db.execSQL("delete from "+NewsSQLiteOpenHelper.PHOTO_LIST_TABLE + " where " +
                    NewsSQLiteOpenHelper.PHOTO_DATE + "< '" + date + "'");
            
            db.execSQL("delete from "+NewsSQLiteOpenHelper.PIC_TABLE + " where " +
                    NewsSQLiteOpenHelper.PIC_DATE + "< '" + statusDate + "'");
            
            db.execSQL("delete from "+NewsSQLiteOpenHelper.ARTICLE_READ_LIST_TABLE + " where " +
                    NewsSQLiteOpenHelper.ARTICLE_READ_DATE + "< '" + statusDate + "'");
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        File f = new File(FileUtils.DetailPageTempDir);
        File f2 = new File(PicUtil.phototempDir);
        File f3 = new File(FileUtils.FileTempDir);
        FileUtils.autoDeleteCacheFile(f, DetailPageBean.ExpiredDuration);
        FileUtils.autoDeleteCacheFile(f2, DetailPageBean.ExpiredDuration);
        FileUtils.autoDeleteCacheFile(f3, DetailPageBean.ExpiredDuration);
    }

}
